﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.Xml.Linq;

namespace SPMetadataManager.Columns
{
    public class Exporter
    {
        public void ExportColumns(string siteUrl, out XElement columns)
        {
            columns = new XElement("Fields");

            try
            {
                columns.SetAttributeValue("SiteCollection", siteUrl);
                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        TaxonomySession session = new TaxonomySession(site);
                        
                        foreach (SPField field in web.AvailableFields)
                        {
                            XElement column = new XElement("Field");
                            column.SetAttributeValue("Name", field.InternalName);
                            column.SetAttributeValue("DisplayName", field.Title);
                            column.SetAttributeValue("Group", field.Group);
                            column.SetAttributeValue("Type", field.TypeAsString);
                            if ((field.TypeAsString == "TaxonomyFieldType") || (field.TypeAsString == "TaxonomyFieldTypeMulti"))
                            {
                                TaxonomyField tf = (from f in web.AvailableFields.OfType<SPField>()
                                                    where string.CompareOrdinal(f.InternalName, field.InternalName) == 0                                                    
                                                    select f).Distinct().First() as TaxonomyField;
                                TermStore store = session.TermStores[tf.SspId];
                                column.SetAttributeValue("TermStore", session.TermStores[tf.SspId].Name);
                                column.SetAttributeValue("TermGroup", session.TermStores[tf.SspId].Name);
                                TermSet termSet = store.GetTermSet(tf.TermSetId);
                                column.SetAttributeValue("TermSet", termSet.Name);                                
                                column.SetAttributeValue("AnchorID", tf.AnchorId);
                            }

                            columns.Add(column);
                        }
                    }
                }

            }
            catch (Exception e)
            {
            }            
        }
    }
}
